package com.jae.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.UnsupportedEncodingException;

public class PasswordUtils {

    public static void main(String[] args) {
        System.out.println(PasswordUtils.encode("token"));
    }

    private static final PasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 密码加密
     * @param rawPassword 前端传过来的密码
     * @return
     */
    public static String encode(String rawPassword) {
        return encoder.encode(rawPassword);
    }

    /**
     * 密码比较是否一致
     * @param rawPaaword	前端传过来的密码
     * @param password		数据库中取出来的密码
     * @return
     */
    public static boolean matches(String rawPaaword,String password) {
        return encoder.matches(rawPaaword, password);
    }


    /**
     * Base64 加密
     * @param pwd
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encryptPasswordBase64(String pwd) throws UnsupportedEncodingException {
        Base64 base64 = new Base64();
        byte[] pwdbyte = pwd.getBytes("utf-8");
        String encodedPwd = base64.encodeToString(pwdbyte);
        return encodedPwd;
    }

    /**
     * Base64 解密
     * @param pwd
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decodePasswordBase64(String pwd) throws UnsupportedEncodingException {
        Base64 base64 = new Base64();
        return new String(base64.decode(pwd), "UTF-8");
    }
}
